package com.slipper.system.dictionary.service;

import java.util.List;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.slipper.system.dictionary.dao.DictionaryDataDao;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.slipper.system.api.dictionary.bo.DictionaryDataBO;
import com.slipper.system.api.dictionary.bo.DictionaryDataBOs;
import com.slipper.common.transaction.ReadTransactional;
import com.slipper.common.transaction.WriteTransactional;
import com.slipper.common.util.Tool;

@Service
@ReadTransactional
public class DictionaryDataService {
    @Resource
    private DictionaryDataDao dictionaryDataDao;
    
    public DictionaryDataBO queryBy(String id){
        return dictionaryDataDao.queryBy(id);
    }
    
    public PageInfo<DictionaryDataBO> queryPage(DictionaryDataBO bo) {
        if ("dicName".equals(bo.getSortField())) {
            bo.setSortField("d.name");
        }
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(dictionaryDataDao.queryList(bo));
    }
    
    @WriteTransactional
    public Integer save(DictionaryDataBO bo){
        int result;
        if (bo.getDataId() != null && !"".equals(bo.getDataId())) {
            result = this.dictionaryDataDao.update(bo);
        } else {
            bo.setDataId(Tool.getUUID());
            result = this.dictionaryDataDao.insert(bo);
        }
        
        return result;
    }
    
    @WriteTransactional
    public Integer delete(DictionaryDataBO bo){
        return dictionaryDataDao.delete(bo);
    }

    public List<DictionaryDataBO> queryList(DictionaryDataBO bo) {
        return dictionaryDataDao.queryList(bo);
    }

    @WriteTransactional
    public Integer saves(DictionaryDataBOs bos) {
        int result = 0;
        for (DictionaryDataBO bo : bos.getList()) {
            bo.setDataId(Tool.getUUID());
            bo.setDicId(bos.getDicId());
            result += dictionaryDataDao.insert(bo);
        }
        return result;
    }

    public int saveByCode(DictionaryDataBOs bos) {
        if (bos.getDicId() == null || "".equals(bos.getDicId())) {
            return 0;
        }
        
        DictionaryDataBO qo = new DictionaryDataBO();
        qo.setDicId(bos.getDicId());
        List<DictionaryDataBO> list = this.queryList(qo);
        
        int result = 0;
        for (DictionaryDataBO temp : bos.getList()) {
            for (DictionaryDataBO bo : list) {
                if (bo.getDicKey().equals(temp.getDicKey())) {
                    bo.setDicValue(temp.getDicValue());
                    result += this.dictionaryDataDao.update(bo);
                }
            }
        }
        return result;
    }
}
